//
//  AddGoodsViewController.m
//  ShangPiBao
//
//  Created by chirui on 2017/10/25.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "AddGoodsViewController.h"

@interface AddGoodsViewController ()
{
    NSData * imageData;
    
    NSString * imageUrl;
}
@property (weak, nonatomic) IBOutlet UITextField *goodsName;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIButton *photoBtn;
@property (weak, nonatomic) IBOutlet UIButton *keepBtn;
@property (nonatomic, strong) SZTextView * detailsTextView;
@property (weak, nonatomic) IBOutlet UIView *bgView;

@end

@implementation AddGoodsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.detailsTextView = [[SZTextView alloc]initWithFrame:CGRectMake(10,100 , WIDTH - 20,200)];
    self.detailsTextView.font = [UIFont systemFontOfSize:15];
    self.detailsTextView.placeholder = @"请输入产品介绍...";
    [self.bgView addSubview:self.detailsTextView];
    
    TitleView(@"添加产品");
    _keepBtn.layer.cornerRadius = 45/2.f;
    _keepBtn.layer.masksToBounds = YES;
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_return" target:self action:@selector(back)];
}
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)photoBtnClick:(id)sender {
    
    [BDImagePicker showImagePickerFromViewController:self allowsEditing:YES finishAction:^(UIImage *image) {
        if (image) {
            
            
            imageData = UIImageJPEGRepresentation(image, 0.4);
            
            CGFloat fixelW = CGImageGetWidth(image.CGImage);
            CGFloat fixelH = CGImageGetHeight(image.CGImage);
            
            NSString * widthStr =   [NSString stringWithFormat:@"%f",fixelW ];
            NSString * heightStr =   [NSString stringWithFormat:@"%f",fixelH ];
            NSLog(@"fw = %f,fh= %f",fixelW,fixelH);
            
//            NSString *systemVersionStr = [[UIDevice currentDevice] systemVersion];
//            NSArray * array  = [systemVersionStr componentsSeparatedByString:@"."];
            
//            NSString * sizeX1Str = [NSString stringWithFormat:@"%.f",0.0];
//            NSString * sizeY1Str = [NSString stringWithFormat:@"%.f",0.0];
//            if ([[array firstObject] intValue]>=11) {
//
//                heightStr = [NSString stringWithFormat:@"%f",fixelH+20];
//
//            }

            [self upIconImageRequestFor:imageData forSize:widthStr andHeight:heightStr];
        }
    }];

}

- (IBAction)KeepBtnClick:(id)sender {
    
    if (_goodsName.text==nil||_goodsName.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入产品名称");
        return;
    }
    if (_detailsTextView.text==nil||_detailsTextView.text.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入产品介绍");
        return;
    }
    if (imageUrl==nil||imageUrl.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请选择照片");
        return;
    }
    
    [self addGoodsRequest];
}

-(void)upIconImageRequestFor:(NSData*)data forSize:(NSString *)flowid andHeight:(NSString *)heig {
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    
//    NSString *systemVersionStr = [[UIDevice currentDevice] systemVersion];
//    NSArray * array  = [systemVersionStr componentsSeparatedByString:@"."];
 
    NSString * sizeX1Str = [NSString stringWithFormat:@"%.f",0.0];
    NSString * sizeY1Str = [NSString stringWithFormat:@"%.f",0.0];
   
    
    NSString * urlStr = [NSString stringWithFormat:@"%@%@?uphone=%@&app=phone&ver=%@&x1=%@&x2=%@&y1=%@&y2=%@&sw=%@&sh=%@",address_url,goodsShop_imageUrl_api,USER_DEFAULTGet(@"phone"),md5ver,sizeX1Str,flowid,sizeY1Str,heig,flowid,heig];
    
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    SHuiMBhubNoTimeStr(@"正在提交...");
    [manager POST:urlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData){
        
        NSString *fileName = @"123456.jpg";
        [formData appendPartWithFileData:data name:@"Filename" fileName:fileName mimeType:@"image/png"];
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        //打印下上传进度
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"err"] intValue]==0) {
            
            
            imageUrl = responseObject[@"data"][0][@"name"];
           
            
            [_photoBtn sd_setBackgroundImageWithURL:ImageUrl(imageUrl) forState:UIControlStateNormal placeholderImage:ImageName(@"icon_products_add")];
            
        }else{
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){
        
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
        
    } ];
    
}

-(void)addGoodsRequest{
    
    NSString * md5ver = [SHJudgeTools md532BitLower:[NSString
                                                     stringWithFormat:@"%@api.shangpibao.com",USER_DEFAULTGet(@"phone")]];
    NSString * parStr = [NSString stringWithFormat:@"%@%@",address_url,add_shops_api];
    
    NSDictionary * dic = @{@"uphone":USER_DEFAULTGet(@"phone"),
                           @"uid":USER_DEFAULTGet(@"uid"),
                           @"ustatus":@"3",
                           @"utitle":_goodsName.text,
                           @"usm":@"",
                           @"unum":@"1",
                           @"ucontent":_detailsTextView.text,
                           @"upicture":imageUrl,
                           @"uclass":USER_DEFAULTGet(@"classId"),
                           @"ver":md5ver};
    
    
    [PostNetWorking postNetWorkingStr:parStr andparameters:dic Success:^(id responseObject) {
        if ([responseObject[@"err"] intValue]==0) {
            
            
            SHuiMBhudTextTimeStr(@"添加成功");
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.navigationController popViewControllerAnimated:YES];
            });
  
        }else{
            
            SHuiMBhudTextTimeStr(EorrMessageStr);
        }

    } failed:^(NSError *error) {
        SHuiMBHidleYes;
        
        SHuiMBhudTextTimeStr(@"网络错误，请稍后再试");
    }];
}


@end
